<?php
 // establish database connection
 establish_db_connection();

 switch($_REQUEST['action']){
   case 'save_message':
     save_message();
     break;
   case 'deliver_message':
     deliver_message();
     break;
 }


 /*
 * Save chat message for later retrieval
 * 
 */
 function save_message(){
   $message = mysql_real_escape_string($_REQUEST['message']);
   $user_id_from = mysql_real_escape_string($_REQUEST['from_user']);
   $user_id_to = mysql_real_escape_string($_REQUEST['to_user']);
   $query = 'INSERT INTO chat_messages (user_id_to, user_id_from, message) VALUES ("'.$user_id_to.'", "'.$user_id_from.'", "'.$message.'");';
   if(mysql_query($query)){
     $return = 'message was saved successfully';
   }else{
     $return = 'message could not be saved!';
   }
   echo $return;
 }
 

 /*
  * Check for new messages for a certain user
  * 
  */
  function deliver_message(){
    $user_id_to = mysql_real_escape_string($_REQUEST['to_user']);
    $query = 'SELECT * FROM chat_messages WHERE user_id_to = "'.$user_id_to.'" ORDER BY id ASC;';
    if($result = mysql_query($query)){
      $status = 'ok';
      while ($row = mysql_fetch_assoc($result)) {
          $data .= '{ "message":"'.stripslashes($row['message']).'", "from_user":"'.$row['user_id_from'].'"},';
      }
      $data = '['.substr($data, 0, -1).']';
      
      // delete messages
      $delete_query = 'DELETE FROM chat_messages WHERE user_id_to = "'.$user_id_to.'";';
      mysql_query($delete_query);
    }else{
      $status = 'query could not be made!';
      $data = '""';
    }
    
    header('Content-type: application/json; charset="utf-8"', true);
    echo '{"status": "'.$status.'", "messages":'.$data.'}';
  }
 
 
 
 
 
 function establish_db_connection(){
   /* Chat messages must be stored in a database table. So please create the following MySQL table:
    * 
       CREATE TABLE IF NOT EXISTS `chat_messages` (
          `id` int(11) NOT NULL auto_increment,
          `user_id_from` varchar(255) NOT NULL,
          `message` text NOT NULL,
          `user_id_to` varchar(255) NOT NULL,
          PRIMARY KEY  (`id`)
        ) ENGINE=MyISAM  DEFAULT CHARSET=utf8;
    */
   // Please provide here the connection information for your MySQL database:
   $host        = 'localhost';
   $db_user     = '';
   $db_password = '';
   $db_name     = '';
   
   mysql_connect($db_host, $db_user, $db_password);
   mysql_selectdb($db_name);
   mysql_query('SET NAMES utf8;');
 }